<template>
	<view class="text-area" style="position: fixed;top: -9999999999999rpx;">
	    <canvas style="width:220rpx;height:86rpx;" canvas-id="logo"></canvas>
	</view>
	<view class="relative">
		<view class="absolute left-0 top-0 w-full h-[150px]" :style="{backgroundColor:bgColor || '#d81e06'}"></view>
		<u-navbar :bgColor="scrollTop > 0 ? bgColor || '#d81e06' : 'transparent'" placeholder>
			<template v-slot:left>
				<image class="w-[40px] h-[40px]" src="/static/logo.png"></image>
			</template>
			<template v-slot:center>
				<view @click="toSearch()" class="flex-1 flex flex-row items-center bg-[#FFFFFF] rounded-[25px] h-[36px] leading-[36px] px-[8px]">
					<u-icon size="24" name="search" :color="bgColor || '#999999'"></u-icon>
					<text class="text-[#999999] text-[14px]">搜索商品关键词</text>
				</view>
			</template>
			<template v-slot:right>
				<view class="flex flex-row items-center">
					<u-avatar v-if="store.user" :src="store.user.Avatar" size="30" class="mr-[4px]"></u-avatar>
					<u-icon @click="changeMode()" :name="listMode == 'list' ? 'grid' : 'list-dot'" size="30" color="#FFFFFF"></u-icon>
				</view>
			</template>
		</u-navbar>
		<u-swiper @click="bannerClick" :loading="bannerLoading" @change="bannerChange" :current="bannerCurrent" bgColor="transparent" circular :list="bannerList"
			keyName="ImageUrl" indicator height="180" class="mx-[16px] my-[10px]">
			<template #indicator>
				<view class="flex flex-row justify-center">
					<view v-for="(item,index) in bannerList" :key="index"
						class="w-[10px] h-[2px] rounded-[2px] mx-[2px]"
						:class="bannerCurrent == index ? 'active-color' : 'inactive-color'"></view>
				</view>
			</template>
		</u-swiper>
		
		<view v-if="false" class="mx-[16px] mt-[20px]">
			<u-scroll-list indicator indicatorColor="#B2B2B2" indicatorActiveColor="#FE0200">
				<view v-for="(item,index) in thumbs" :key="index" class="mr-[20px]">
					<u-image :src="item.thumb" width="80px" height="80px"></u-image>
				</view>
			</u-scroll-list>
		</view>
		
		<u-text text="新客专区" align="center" size="28"></u-text>
		<u-text text="New Customer Zone" align="center" size="16" color="#999999"></u-text>
		<goods-list :list="goodList1" :mode="listMode"></goods-list>
		<u-text text="复购专区" align="center" size="28" v-if="goodList2.length > 0"></u-text>
		<goods-list :list="goodList2" :mode="listMode"></goods-list>
		<u-text text="消费专区" align="center" size="28" v-if="goodList3.length > 0"></u-text>
		<goods-list :list="goodList3" :mode="listMode"></goods-list>
		<u-loadmore line height="40" marginTop="0" marginBottom="0" status="nomore" nomoreText="暂无更多商品"></u-loadmore>
	</view>
	<u-tabbar value="home" activeColor="#d81e06">
		<u-tabbar-item text="首页" name="home">
			<template #active-icon>
				<image class="w-[20px] h-[20px]" src="/static/home_select.png"></image>
			</template>
			<template #inactive-icon>
				<image class="w-[20px] h-[20px]" src="/static/home.png"></image>
			</template>
		</u-tabbar-item>
		<u-tabbar-item text="二维码" name="qrcode" @click="onIntroduceClick" v-if="store.isLogin" >
			<template #active-icon>
				<image class="w-[20px] h-[20px]" src="/static/qrcode.svg"></image>
			</template>
			<template #inactive-icon>
				<image class="w-[20px] h-[20px]" src="/static/qrcode.svg"></image>
			</template>
		</u-tabbar-item>
		<u-tabbar-item text="个人中心" name="user" @click="onUserClick">
			<template #active-icon>
				<image class="w-[20px] h-[20px]" src="/static/user_select.png"></image>
			</template>
			<template #inactive-icon>
				<image class="w-[20px] h-[20px]" src="/static/user.png"></image>
			</template>
		</u-tabbar-item>
	</u-tabbar>
</template>

<script setup>
	import { ref, unref } from "vue";
	import * as api from "@/api.js";
	import * as uniapp from "@dcloudio/uni-app";
	import { useUserStore } from "@/store/config.js";
	import goodsList from "@/components/goodsList/goodsList";
	import checkVersion from '@/pages/lq-upgrade/checkVersion.js';
	
	uni.hideTabBar({
		success:()=>{
			
		},
		fail:(err)=>{
			console.log(err);
		}
	});
	
	const store = useUserStore();

	const bannerList = ref([]);
	const bannerLoading = ref(false);
	const bannerCurrent = ref(0);
	const bannerImageList = ref([]);
	
	const bannerChange = e => {
		bannerCurrent.value = e.current;
		if(bannerImageList.value[e.current]) {
			bgColor.value = bannerImageList.value[e.current]
		} else {
			getImage(e.current);
		}
	}
	const bannerClick = e => {
		if(bannerList.value[e].HasContent) {
			uni.navigateTo({
				url:`/pages/richView/richView?id=${unref(bannerList)[e].AdvID}`
			})
		}
	}
	
	const isShowing = ref(false);
	const bgColor = ref('');
	const listMode = ref('grid');
	const scrollTop = ref(0);
	
	const changeMode = () => {
		unref(listMode) == 'grid' ? listMode.value = 'list' : listMode.value = 'grid'
	}
	
	const toSearch = () => {
		uni.navigateTo({
			url:`/pages/search/search`
		})
	}
	
	const thumbs = ref([{
			thumb: "https://cdn.uviewui.com/uview/goods/1.jpg"
		}, {
			thumb: "https://cdn.uviewui.com/uview/goods/2.jpg"
		}, {
			thumb: "https://cdn.uviewui.com/uview/goods/3.jpg"
		}, {
			thumb: "https://cdn.uviewui.com/uview/goods/4.jpg"
		}, {
			thumb: "https://cdn.uviewui.com/uview/goods/5.jpg"
		},
	])
	
	const goodList1 = ref([]);
	const goodList2 = ref([]);
	const goodList3 = ref([]);
	
	uniapp.onLoad(option => {
		getAdList();
		getGoodsList(1);
		getGoodsList(2);
		getGoodsList(3);
		upgrade();
	})	
	
	uniapp.onPageScroll(e => {
		scrollTop.value = e.scrollTop;
	})
	
	uniapp.onReachBottom(() => {
		
	})
	
	uniapp.onPullDownRefresh(async () =>{
		getAdList();
		getGoodsList(1);
		getGoodsList(2);
		// getGoodsList(3);
		await uni.$u.sleep(500);
		uni.stopPullDownRefresh();
	})
	
	uniapp.onShow(() => {
		isShowing.value = true;
	})
	
	uniapp.onHide(() => {
		isShowing.value = false;
	})
	
	
	const getAdList = async () => {
		bannerLoading.value = true;
		const result = await api.getAdList();
		if(result[0]) {
			bannerLoading.value = false;
			bannerList.value = result[0];
			bannerImageList.value = [];
			getImage(0);
		}
	}
	
	const getGoodsList = async (category) => {
		const result = await api.getHomeGoods(category);
		if(result[0]){
			switch(category){
				case 1:
					goodList1.value = result[0];
					break;
				case 2:
					goodList2.value = result[0];
					break;
				case 3:
					goodList3.value = result[0];
					break
			}
		}
	}
	
	const onUserClick = () => {
		uni.switchTab({
			url:`/pages/user/user`
		})
	}
	
	const onIntroduceClick = () => {
		uni.navigateTo({
			url:`/pages/introduce/introduce`
		})
	}
	
	const upgrade = async () => {
		const version = uni.getSystemInfoSync().appVersion;
		const result = await api.updateVersion(version);
		console.log(result);
		if(result[0] && result[0].IsUpdate === 1) {
			checkVersion({
				name:result[0].CurrentVersion,
				code:'',
				content:'',
				url:uni.getSystemInfoSync().platform === 'android' ? result[0].ApkUrl : result[0].IosUrl,
				forceUpdate: false
			})
		}
	}
	
	function getImage(index) {
		if(!unref(isShowing)) return
		// 获得图片信息
		uni.getImageInfo({
			// 注意图片的地址
			src: unref(bannerList)[unref(bannerCurrent)]['ImageUrl'],
			success(res) {
				let imgHeight = 100;
				let imgWidth = 100;
				var ctx = uni.createCanvasContext("logo") // 使用画布创建上下文 图片
				ctx.drawImage(res.path, 0, 0, 100, 100) // 设置图片坐标及大小，括号里面的分别是（图片路径，x坐标，y坐标，width，height）
				ctx.draw(false, async () => {
					await new Promise(resolve => setTimeout(() => resolve(),100))
					uni.canvasGetImageData({
						canvasId: 'logo',
						x: 0,
						y: 0,
						width: 100,
						height: 100,
						success: (res) => {
							let data = res.data;
							const arr = Array.prototype.slice.call(data, 0)
							var r = 1,
								g = 1,
								b = 1,
								a = 1;
							// 取所有像素的平均值
							for (var i = 0; i < arr.length; i += 4) {
								r += arr[i];
								g += arr[i+1];
								b += arr[i+2];
								a += arr[i+3];
							}							
							// 求取平均值
							r /= (imgWidth * imgHeight);
							g /= (imgWidth * imgHeight);
							b /= (imgWidth * imgHeight);
							a /= (imgWidth * imgHeight);
							
							// 将最终的值取整
							r = Math.round(r);
							g = Math.round(g);
							b = Math.round(b);
							a = Math.round(a*100/256)/100;
							let obj = {
								r,
								g,
								b,
								a
							}
							let rgbaA = 'rgba(' + obj.r + ',' + obj.g + ',' + obj.b +
								',' +
								1 + ')'
							bgColor.value = rgbaA
							bannerImageList.value[index] = rgbaA
						},
						fail: (fail) => {
							console.log(fail)
						}
					})
				})
			}
		})
	}
</script>

<style>
	page{
		background-color: #f8f8f8;
	}
</style>
<style lang="scss" scoped>
	
	::v-deep .u-navbar__content__left{
		position: relative !important;
	}
	
	::v-deep .u-navbar__content__right{
		position: relative !important;
	}
	.inactive-color {
		background-color: #B2B2B2;
	}

	.active-color {
		background-color: #FE0200;
	}
</style>